package cn.ibent.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.ibent.common.BlindRelayHandler;
import cn.ibent.common.SocketChannelUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;

public class SslEventHandler extends ChannelInboundHandlerAdapter {
    private static final Logger log = LoggerFactory.getLogger(SslEventHandler.class);

    private final Channel relay;

    public SslEventHandler(Channel relay) {
        this.relay = relay;
    }
    
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof SslHandshakeCompletionEvent) {
            SslHandshakeCompletionEvent sslComplete = (SslHandshakeCompletionEvent) evt;
            if (sslComplete.isSuccess()) {
                if (ctx.channel().isActive()) {
                    ctx.pipeline().remove(this);
                    ctx.pipeline().addLast(new HttpClientCodec());
                    ctx.pipeline().addLast(new BlindRelayHandler(relay));
                }
                if (relay.isActive()) {
                    relay.pipeline().addLast(new BlindRelayHandler(ctx.channel()));
                    relay.config().setAutoRead(true);
                }
            } else {
                ctx.close();
                SocketChannelUtils.closeOnFlush(relay);
            }
        }
        super.userEventTriggered(ctx, evt);
    }
}
